package cloud.keveri.chat4j.api;

import cloud.keveri.chat4j.api.forest.ChatLogHandler;
import com.dtflys.forest.Forest;
import cloud.keveri.chat4j.api.interceptor.HeaderMaskInterceptor;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSources;

import java.util.concurrent.TimeUnit;

/**
 * 未来处理上下文问题
 * <p>
 * 作者：沈自在
 **/
public abstract class AbstractChatBlender implements ChatBlender {

    /**
     *
     */
    protected OkHttpClient httpClient;

    /**
     *
     */
    private boolean forestInitSign = false;


    /**
     * Chat Config 暂存
     */
    private static final class ChatConfigHolder {
        private static ChatConfig config = ChatConfig.builder().build();
    }

    protected AbstractChatBlender() {
        init();
    }

    /**
     * 获取
     */
    public static ChatConfig getChatConfig() {
        return ChatConfigHolder.config;
    }

    /**
     * 设置
     */
    public static void setChatConfig(ChatConfig config) {
        ChatConfigHolder.config = config;
    }

    /**
     * 初始化
     */
    protected void init() {
        // 1. 提取配置
        ChatConfig config = getChatConfig();

        // 2. 初始化 HttpClient (仅用于流式会话)
        httpClient = new OkHttpClient
                .Builder()
                .connectTimeout(config.getConnectTimeout(), TimeUnit.SECONDS)
                .addInterceptor(new HeaderMaskInterceptor())
                .writeTimeout(config.getWriteTimeout(), TimeUnit.SECONDS)
                .readTimeout(config.getReadTimeout(), TimeUnit.SECONDS)
                .build();

        // 3. 初始化 forest
        if (!forestInitSign) {
            Forest.config()
                    .setMaxRetryCount(config.getRetryCount())
                    .setReadTimeout(config.getReadTimeout(), TimeUnit.SECONDS)
                    .setConnectTimeout(config.getConnectTimeout(), TimeUnit.SECONDS)
                    .setLogHandler(new ChatLogHandler())
            ;

            // 回置标记
            forestInitSign = true;
        }
    }


    /**
     * 添加拦截器
     */
    public void addInterceptor(Interceptor interceptor) {
        httpClient.interceptors().add(interceptor);
    }

    /**
     * create factory
     */
    protected EventSource.Factory createRequestFactory() {
        return EventSources.createFactory(httpClient);
    }
}